package array_0823;

import com.sun.xml.internal.ws.api.model.wsdl.WSDLOutput;

public class ArrayPractice {
    public static void main(String[] args) {
        int arr[]=new int[]{1,2,3,4,5,6};
        int arr1[]={1,4,2,8,2,4,0,8};
        System.out.println("平均值："+avg(arr));
        System.out.println("下标位置："+find(arr,4));
        System.out.println("下标位置："+find(arr,11));
        System.out.println("下标位置："+binarySearch(arr,6));
        System.out.println("下标位置："+recursionBinary(arr,0,5,3));
        contrayArray(arr);
        System.out.print("逆序输出：");
        for(int i:arr)
            System.out.print(i+" ");
        System.out.println();

        System.out.print("冒泡排序：");
        bubbleSort(arr1);
        for(int i:arr1)
            System.out.print(i+" ");
    }

    public static void bubbleSort(int arr[]){//冒泡排序
        for(int i=0;i<arr.length;i++){
            for(int j=0;j<arr.length-i-1;j++){//-1防止数组越界
                if(arr[j]>arr[j+1]){
                    int tmp=arr[j];
                    arr[j]=arr[j+1];
                    arr[j+1]=tmp;
                }
            }
        }
    }
    public static void contrayArray(int arr[]){//逆序输出
        int left =0;
        int right=arr.length-1;
        while(left<right){
            int tmp=arr[right];
            arr[right]=arr[left];
            arr[left]=tmp;
            left++;
            right--;
        }

    }
    public static int recursionBinary(int arr[],int left,int right,int toFind){//用递归二分查找，必须是有序数组
        if(left>right)//注意不要等于！
            return -1;
        int mid=left+((right-left)>>1);
        if(arr[mid]==toFind)
            return mid;
        else if (arr[mid]<toFind) {
            return recursionBinary( arr,mid+1,right,toFind);
        }
        return recursionBinary( arr,left,mid-1,toFind);

    }
    public static int binarySearch(int arr[],int toFind){//二分查找，必须是有序数组
        int left=0;
        int right=arr.length-1;
        int mid=left+((right-left)>>1) ;
        while(left<=right){
            if(toFind<arr[mid]){
                right=mid-1;
                mid=left+((right-left)>>1) ;
            }
            else if(toFind>arr[mid]){
                left=mid+1;
                mid=left+((right-left)>>1) ;
            }
            else {
                return mid;
            }
        }
        return-1;
    }
    public static int find(int arr[],int toFind){//找到返回下标，找不到返回0
        for(int i=0;i<arr.length;i++){
            if(arr[i]==toFind)
                return i;
        }
        return -1;
    }
    public static double avg(int []arr){//模拟 计算传入数组平均值
        int sum=0;
        for(int i:arr){
            sum+=i;
        }
        return sum/(arr.length*1.0);
    }
}
